package com.demo.k8s.provider.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

@Slf4j
@RestController
public class ProviderController {

    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/service")
    public List<String> getServiceList(){
        List<String> services = discoveryClient.getServices();
        log.info("services = " + services);
        return services;
    }

    /**
     * 被service-k8s项目调用
     * @param name 请求参数
     * @return 返回信息
     */
    @GetMapping("/provider")
    public String provider(@RequestParam("name") String name) throws UnknownHostException {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        log.info("参数name = {}，请求header = {}", name, request.getHeader("end-user"));
        return String.format("参数 name = %s， service-k8s-provider ip:%s", name, InetAddress.getLocalHost());
    }
}
